//
//  ZVScrollSider.m
//  scrllSlider
//
//  Created by 子为 on 15/12/25.
//  Copyright © 2015年 wealthBank. All rights reserved.
//


#define dialColorGrayscale 0.789 //刻度的颜色灰度
#define textColorGrayscale 0.629 //文字的颜色灰度
#define textRulerFont [UIFont systemFontOfSize:9]

#define dialGap [UIScreen mainScreen].bounds.size.width /40  //刻度盘的间距  6分钟
#define dialLong 15//刻度盘长的
#define dialShort 8 //刻度盘短

#import "ZVScrollSlider.h"

#pragma mark - -------------------------------ZVRulerView  is  UICollectionView cell--------------------------------

@interface  ZVRulerView : UIView
@property (nonatomic, assign) int minValue;
@property (nonatomic, assign) int maxValue;
@property (nonatomic, assign) int item;
@property (nonatomic, copy) NSString *unit;
@property (nonatomic, assign) int  intervalDay;//间隔天数

@end

@implementation ZVRulerView

//当前日期距离几天前的日期
- (NSDate *)currentDateIntervalDay:(int32_t)day {
    NSDate *currentDate = [NSDate date];
    NSDate *appointDate;// 指定日期声明
    NSTimeInterval oneDay = 24 * 60 * 60;  // 一天一共有多少秒
    appointDate = [currentDate initWithTimeIntervalSinceNow: -(oneDay * day)];
    NSLog(@"appointDate==%@",appointDate);
    return appointDate;
}

/**
 日期转字符串
 
 @param date date
 @param format @"MM-dd"
 @return @"12:10"
 */
- (NSString *)dateWithStr:(NSDate *)date format:(NSString *)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (!format) {
        format = @"MM-dd";
    }
    formatter.dateFormat = format;
    NSString *strDate = [formatter stringFromDate:date];
    return strDate;
}

#pragma mark - 绘制标尺view
- (void)drawRect:(CGRect)rect
{
    //计算位置
    CGFloat startX = 0;
    CGFloat lineCenterX = dialGap;//10
    CGFloat shortLineY = rect.size.height - dialShort;//42
    CGFloat longLineY =  rect.size.height - dialLong;//35
    CGFloat bottomY = rect.size.height;//50
    if (_maxValue == 0) {
        _maxValue = 1000;
    }
    //一个刻度占的大小
    CGFloat step = (_maxValue-_minValue) / 10;//单个cell的最大和最小值
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
    CGContextSetRGBStrokeColor(context, 1, 1, 1, 1);//设置线的颜色, 如果不设置默认是黑色的
    CGContextSetLineWidth(context, 1);//设置线的宽度, 默认是1像素
    CGContextSetLineCap(context, kCGLineCapButt);  //kCGLineCapRound 线两头是圆弧  kCGLineCapButt  无端点
    
    //绘制上面的刻度
    for (int i = 0; i <= 10; i++) {//10个刻度
        if (i % 10 == 0) {//除以10取余数等于0   0 10 20 30 40
            CGContextMoveToPoint(context, startX + lineCenterX  * i - 1, 0);//绘制长的刻度 起使点
            CGContextAddLineToPoint(context, startX + lineCenterX * i - 1 , dialLong);
        } else {//绘制短的刻度
            CGContextMoveToPoint(context, startX + lineCenterX  * i, 0);//绘制长的刻度 起使点
            CGContextAddLineToPoint(context, startX + lineCenterX * i, dialShort);
        }
        CGContextStrokePath(context);//开始绘制
    }
  
    //绘制下面的刻度
    for (int i = 0; i <= 10; i++) {
        if (i % 10 == 0) {//除以10取余数等于0   0 10 20 30 40
            NSString *Num  = nil;
            CGContextMoveToPoint(context, startX + lineCenterX * i - 1, longLineY);//起点
            int32_t value = (i * step + _minValue)/60;
            value = value % 24;
            if (value != 0) {
                if (value < 10) {
                    Num = [NSString stringWithFormat:@"0%d:00%@", value , _unit];
                } else {
                    Num = [NSString stringWithFormat:@"%d:00%@", value , _unit];
                }
            } else {
                int32_t interval;
                if (_minValue == 0) {
                    interval = 1;
                } else {
                    if (self.item % 24 == 0 ) {//可以整除的  24的倍数
                        interval = self.item / 24;
                    } else {
                        interval = round((CGFloat)self.item / (CGFloat)24) + 1;
                    }
                }
                
                NSLog(@"interval=%d self.item=%d", interval, self.item);
                interval = _intervalDay - interval;
                NSDate *intervalDate = [self currentDateIntervalDay:interval];
                NSString *strDate = [self dateWithStr:intervalDate format:nil];
                Num = [NSString stringWithFormat:@"%@%@", strDate , _unit];
            }
            NSDictionary *attribute = @{NSFontAttributeName:textRulerFont,
                                        NSForegroundColorAttributeName:[UIColor whiteColor]};
            
            CGFloat width = [Num boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:0 attributes:attribute context:nil].size.width;
            //绘制文字
            [Num drawInRect:CGRectMake(startX + lineCenterX * i - width/2, longLineY - 14, width, 14) withAttributes:attribute];
            CGContextAddLineToPoint(context, startX + lineCenterX * i - 1 , bottomY);//终点

        } else {
            CGContextMoveToPoint(context, startX + lineCenterX * i, shortLineY);//起点
            CGContextAddLineToPoint(context, startX + lineCenterX * i, bottomY);//终点

        }
        CGContextStrokePath(context);//开始绘制
    }
    
  //绘制矩形
//    for (int i = 0; i <= 10; i++) {
//        if (i % 2 == 0) {//偶数画上矩形
//            CGContextAddRect(context, CGRectMake(startX + lineCenterX * i, 0, lineCenterX, rect.size.height));
//            CGContextSetFillColorWithColor(context, [UIColor darkGrayColor].CGColor);
//        }
//        CGContextFillPath(context);//开始绘制
//    }
   
}

@end

#pragma mark - -------------------------------ZVFooterRulerView--------------------------------

@interface ZVFooterRulerView : UIView
@property (nonatomic, copy) NSString *unit;

@end

@implementation ZVFooterRulerView

- (void)drawRect:(CGRect)rect
{
    CGFloat startX =-0.5;

    CGFloat longLineY = rect.size.height - dialLong;
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 0, 0, 1, 1);//设置线的颜色, 如果不设置默认是黑色的
    CGContextSetLineWidth(context, 1.0);//设置线的宽度, 默认是1像素
    CGContextSetLineCap(context, kCGLineCapButt);
    
    CGContextMoveToPoint(context, startX, longLineY);//起使点
    NSDate *intervalDay = [self currentDateIntervalDay:1];
    NSString *strDate = [self dateWithStr:intervalDay format:nil];
    NSString *Num = [NSString stringWithFormat:@"%@%@", strDate , _unit];
    
    NSDictionary *attribute = @{NSFontAttributeName:textRulerFont,
                                NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGFloat width = [Num boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:0 attributes:attribute context:nil].size.width;
    [Num drawInRect:CGRectMake(0-width/2, longLineY-14, width, 14) withAttributes:attribute];
    CGContextAddLineToPoint(context, startX, rect.size.height);
    CGContextStrokePath(context);//开始绘制
    CGContextMoveToPoint(context, startX, 0);//起使点
    CGContextAddLineToPoint(context, startX, dialLong);
    CGContextStrokePath(context);//开始绘制
}

//当前日期距离几天前的日期
- (NSDate *)currentDateIntervalDay:(int32_t)day {
    NSDate *currentDate = [NSDate date];
    NSDate *appointDate;// 指定日期声明
    NSTimeInterval oneDay = 24 * 60 * 60;  // 一天一共有多少秒
    appointDate = [currentDate initWithTimeIntervalSinceNow: (oneDay * day)];
    NSLog(@"appointDate==%@",appointDate);
    return appointDate;
}

/**
 日期转字符串
 
 @param date date
 @param format @"MM-dd"
 @return @"12:10"
 */
- (NSString *)dateWithStr:(NSDate *)date format:(NSString *)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (!format) {
        format = @"MM-dd";
    }
    formatter.dateFormat = format;
    NSString *strDate = [formatter stringFromDate:date];
    return strDate;
    
}
@end

#pragma mark - ------------------------------- ZVHeaderRulerView--------------------------------
@interface ZVHeaderRulerView : UIView
@property (nonatomic, copy) NSString *unit;
@property (nonatomic, assign) int              intervalDay;//间隔天数

@end

@implementation ZVHeaderRulerView

- (void)drawRect:(CGRect)rect
{
    CGFloat longLineY = rect.size.height - dialLong;
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 0, 1, 0, 1);//设置线的颜色, 如果不设置默认是黑色的
    CGContextSetLineWidth(context, 1.0);//设置线的宽度, 默认是1像素
    CGContextSetLineCap(context, kCGLineCapButt);
    CGContextMoveToPoint(context, rect.size.width , longLineY);//起使点
    NSString *Num = nil;
    NSDate *intervalDate = [self currentDateIntervalDay:_intervalDay -1];
    NSString *strDate = [self dateWithStr:intervalDate format:nil];
    Num = [NSString stringWithFormat:@"%@%@", strDate , _unit];
    NSDictionary *attribute = @{NSFontAttributeName:textRulerFont,
                                NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGFloat width = [Num boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:0 attributes:attribute context:nil].size.width;
    [Num drawInRect:CGRectMake(rect.size.width-width/2, longLineY-14, width, 14) withAttributes:attribute];
    
    CGContextAddLineToPoint(context, rect.size.width, rect.size.height);
    CGContextStrokePath(context);//开始绘制
    
    CGContextMoveToPoint(context, rect.size.width, 0);//起使点
    CGContextAddLineToPoint(context, rect.size.width, dialLong);//结束点
    CGContextStrokePath(context);//开始绘制
    
}

//当前日期距离几天前的日期
- (NSDate *)currentDateIntervalDay:(int32_t)day {
    NSDate *currentDate = [NSDate date];
    NSDate *appointDate;// 指定日期声明
    NSTimeInterval oneDay = 24 * 60 * 60;  // 一天一共有多少秒
    appointDate = [currentDate initWithTimeIntervalSinceNow: -(oneDay * day)];
    NSLog(@"appointDate==%@",appointDate);
    return appointDate;
}


/**
 日期转字符串
 
 @param date date
 @param format @"MM-dd"
 @return @"12:10"
 */
- (NSString *)dateWithStr:(NSDate *)date format:(NSString *)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (!format) {
        format = @"MM-dd";
    }
    formatter.dateFormat = format;
    NSString *strDate = [formatter stringFromDate:date];
    
    return strDate;
    
}
@end

#pragma mark - -------------------------------ZVScrollSlider--------------------------------

@interface ZVScrollSlider ()<UIScrollViewDelegate,UITextFieldDelegate,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UIButton         *deleteBtn;
@property (nonatomic, strong) UILabel          *titleLabel;
@property (nonatomic, strong) UITextField      *valueTF;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIImageView      *redLine;
@property (nonatomic, strong) UIImageView      *bottomLine;



@property (nonatomic, assign) int              stepNum;
@property (nonatomic, assign) int              value;
@property (nonatomic, assign) int              intervalDay;//间隔天数

@property (nonatomic, assign) BOOL             scrollByHand;

@property (nonatomic, assign) CFRunLoopTimerRef timer;


@end

@implementation ZVScrollSlider

- (instancetype)initWithFrame:(CGRect)frame Title:(NSString *)title MinValue:(int)minValue MaxValue:(int)maxValue Step:(int)step Unit:(NSString *)unit HasDeleteBtn:(BOOL)hasDeleteBtn {
    if (self = [super initWithFrame:frame]) {
        //readOnly设置
        _title = title;
        _minValue = minValue;
        _maxValue = maxValue;
        _step = step;
        //cell个数
        _stepNum = maxValue;
        _unit = unit;
        _scrollByHand = NO;
        _intervalDay = maxValue/24;
        self.backgroundColor = [UIColor blackColor];
        
        //删除按钮
        _deleteBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 40, 18, 18)];
        [_deleteBtn setBackgroundImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
        [_deleteBtn setBackgroundImage:[UIImage imageNamed:@"删除"] forState:UIControlStateHighlighted];
        [_deleteBtn setBackgroundColor:[UIColor redColor]];
        _deleteBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        _deleteBtn.layer.cornerRadius = 9;
        _deleteBtn.layer.masksToBounds = YES;
        [_deleteBtn addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
        if (hasDeleteBtn) {
            [self addSubview:_deleteBtn];
        }
        
#pragma mark - 名称Label
        CGFloat height = [_title boundingRectWithSize:CGSizeMake(frame.size.width-10-18-6-15, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.height;
        
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10+18+6, 40, frame.size.width-10-18-6-15, height)];
        
        if (!hasDeleteBtn) {
            _titleLabel.frame = CGRectMake(15, 15, frame.size.width-30, height);
        }
        _titleLabel.font          = [UIFont systemFontOfSize:14];
        _titleLabel.numberOfLines = 0;
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.text          = _title;
        _titleLabel.textColor     = [UIColor whiteColor];
        [self addSubview:_titleLabel];
        
#pragma mark - 输入框
        _valueTF                          = [[UITextField alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_titleLabel.frame) + 5, frame.size.width, 20)];
        
        _valueTF.defaultTextAttributes    = @{NSUnderlineColorAttributeName:[UIColor orangeColor],//下划线颜色
                                              NSUnderlineStyleAttributeName:@(1),//下划线
                                              NSFontAttributeName:[UIFont systemFontOfSize:18],
                                              NSForegroundColorAttributeName:[UIColor whiteColor]};
        
        _valueTF.textAlignment            = NSTextAlignmentCenter;
        _valueTF.delegate                 = self;
        _valueTF.keyboardType             = UIKeyboardTypeNumberPad;
        
        NSDictionary *dict = @{NSUnderlineColorAttributeName:[UIColor lightGrayColor],//设置下划线颜色
                               NSUnderlineStyleAttributeName:@(1),//设置下划线
                               NSFontAttributeName:[UIFont systemFontOfSize:12],
                               NSForegroundColorAttributeName:[UIColor whiteColor]};
        
        _valueTF.attributedPlaceholder    = [[NSAttributedString alloc] initWithString:@"滑动标尺或输入"
                                                                            attributes:dict];
        [self addSubview:_valueTF];
        
#pragma mark - 油标尺
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];//水平方向
        flowLayout.minimumLineSpacing = 0;
        [flowLayout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        
        _collectionView  = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_valueTF.frame) + 3, self.bounds.size.width, 50) collectionViewLayout:flowLayout];
        // _collectionView.transform = CGAffineTransformMakeRotation(M_PI);
        _collectionView.backgroundColor = [UIColor blackColor];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"systemCell"];
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"custemCell"];
        
        _collectionView.bounces = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [self addSubview:_collectionView];
        
#pragma mark - 竖直中线
        _redLine = [[UIImageView alloc] initWithFrame:CGRectMake(self.bounds.size.width/2-0.5, CGRectGetMaxY(_valueTF.frame)+5, 1, 45)];
        _redLine.backgroundColor = [UIColor orangeColor];
        [self addSubview:_redLine];
        
#pragma mark - 底部线
        
        UIImageView *bottomLine1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, CGRectGetMinY(_collectionView.frame)-2, self.bounds.size.width, 1)];
        bottomLine1.backgroundColor = [UIColor whiteColor];
        [self addSubview:bottomLine1];
        
        _bottomLine = [[UIImageView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_collectionView.frame), self.bounds.size.width,1)];
        _bottomLine.backgroundColor = [UIColor whiteColor];
        [self addSubview:_bottomLine];
    }
    return self;
}
//当前日期距离几天前的日期
- (NSDate *)currentDateIntervalDay:(int32_t)day {
    NSDate *currentDate = [NSDate date];
    NSDate *appointDate;// 指定日期声明
    NSTimeInterval oneDay = 24 * 60 * 60;  // 一天一共有多少秒
    appointDate = [currentDate initWithTimeIntervalSinceNow: -(oneDay * day)];
    NSLog(@"appointDate==%@",appointDate);
    return appointDate;
}

- (void)updateOffset {
    NSLog(@"一个刻度偏移量：%f",dialGap);
    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:currentDate];
    NSInteger year = [dateComponent year];
    NSInteger month =  [dateComponent month];
    NSInteger day = [dateComponent day];
    NSInteger hour =  [dateComponent hour];
    NSInteger minute =  [dateComponent minute];
    NSInteger second = [dateComponent second];
    NSLog(@"year is: %ld", (long)year);
    NSLog(@"month is: %ld", (long)month);
    NSLog(@"day is: %ld", (long)day);
    NSLog(@" hour is: %ld",  (long)hour);
    NSLog(@"minute  is: %ld", (long)minute );
    NSLog(@"second is: %ld", (long)second);
    CGFloat dayOffset = (CGFloat)((_intervalDay - 1) * 24.0 * 10.0 * dialGap);
    CGFloat minuteOffset = (CGFloat)(minute / 6.00f) * dialGap;//9.375000
    CGFloat hourOffset = (CGFloat)hour * 10.00f * dialGap;
    _collectionView.contentOffset = CGPointMake(dayOffset + minuteOffset + hourOffset, 0);
    _valueTF.text = [NSString stringWithFormat:@"%@ %ld:%ld", [self dateWithStr:[NSDate date] format:nil] , (long)hour, minute];
}
/**
 日期转字符串

 @param date date
 @param format @"MM-dd"
 @return @"12:10"
 */
- (NSString *)dateWithStr:(NSDate *)date format:(NSString *)format {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (!format) {
        format = @"MM-dd";
    }
    formatter.dateFormat = format;
    NSString *strDate = [formatter stringFromDate:date];
    return strDate;
}

/* 把scrollView 偏移到中心位置 **/
- (void)setScrollViewContentOffsetCenter {
    
    [_collectionView setContentOffset:CGPointMake(CGRectGetWidth(_collectionView.bounds), 0) animated:NO];
}

+ (CGFloat)heightWithBoundingWidth:(CGFloat )width Title:(NSString *)title {
    CGFloat height  = [title boundingRectWithSize:CGSizeMake(width-10-18-6-15, CGFLOAT_MAX)
                                          options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                       attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}
                                          context:nil].size.height;
    return 40+height+10+20+50;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    NSLog(@"layoutSubviews");
    [self updateOffset];
}

#pragma setter
- (void)setRealValue:(float)realValue {
    [self setRealValue:realValue Animated:NO];
}

- (void)setTitle:(NSString *)title {
    _title = title;
    _titleLabel.text = _title;
}

#pragma mark - 设置scrollView的新偏移量 这个就会调用 scrollViewDidScroll 代理
- (void)setRealValue:(float)realValue Animated:(BOOL)animated {
    _realValue = realValue;
    CGFloat offset = realValue * dialGap;
    _valueTF.text = [self offsetWithSize:realValue];
    [_collectionView setContentOffset:CGPointMake(offset, 0) animated:animated];
    //NSLog(@"_realValue==%f  offset == %f",_realValue,  offset);
    if (self.delegate && [self.delegate respondsToSelector:@selector(ZVScrollSlider:ValueChange:)]) {
        [self.delegate ZVScrollSlider:self ValueChange:realValue*_step];
    }
}

#pragma UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *newStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
//    if ([newStr intValue] > _maxValue) {
//        _valueTF.text = [NSString stringWithFormat:@"%d",_maxValue];
//        [self performSelector:@selector(didChangeValue) withObject:nil afterDelay:0];
//        return NO;
//    } else {
        _scrollByHand = NO;
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        [self performSelector:@selector(didChangeValue) withObject:nil afterDelay:1];
        return YES;
//    }
}

- (void)didChangeValue {
    if ([_valueTF.text containsString:@":"]) {
        NSArray *arr = [_valueTF.text componentsSeparatedByString:@":"];
        CGFloat minValue = [arr[1] integerValue] / 6.0;
        CGFloat value = [arr[0] floatValue] * 10 + minValue;
        [self setRealValue:value Animated:YES];
    }
}

- (void)deleteAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(ZVScrollSliderDidDelete:)]) {
        [self.delegate ZVScrollSliderDidDelete:self];
    }
}

#pragma mark UICollectionViewDataSource & Delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSLog(@"多少个cell ====%d", 2 + _stepNum);
    return 2 + _stepNum;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == 0 || indexPath.item == _stepNum+1) {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"systemCell" forIndexPath:indexPath];
            if (indexPath.item == 0) {//在段头上绘制第一个最小刻度
                ZVHeaderRulerView * header = [cell.contentView viewWithTag:1000];
                if (!header) {
                    header = [[ZVHeaderRulerView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width/2, 50)];
                    header.tag = 1000;
                    header.backgroundColor = [UIColor blackColor];
                    header.unit            = _unit;
                    header.intervalDay = _intervalDay;
                    [cell.contentView addSubview:header];
                } else {
                    [header removeFromSuperview];
                    header = [[ZVHeaderRulerView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width/2, 50)];
                    header.tag = 1000;
                    header.backgroundColor = [UIColor blackColor];
                    header.unit            = _unit;
                    header.intervalDay = _intervalDay;
                    [cell.contentView addSubview:header];
                }
            } else {//设置段尾
                //在段尾上绘制第一个最大刻度
                ZVFooterRulerView * footer = [cell.contentView viewWithTag:2000];
                if (!footer) {
                 footer = [[ZVFooterRulerView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width/2, 50)];
                footer.tag = 2000;
                footer.backgroundColor = [UIColor blackColor];
                footer.unit = _unit;
                [cell.contentView addSubview:footer];
             } else {
                
                [footer removeFromSuperview];
                 footer = [[ZVFooterRulerView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width/2, 50)];
                 footer.tag = 2000;
                 footer.backgroundColor = [UIColor blackColor];
                 footer.unit = _unit;
                 [cell.contentView addSubview:footer];
                }
            }
      
        
        return cell;
    } else {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"custemCell" forIndexPath:indexPath];
        ZVRulerView *ruleView = [cell.contentView viewWithTag:9527];
        if (!ruleView) {
            ruleView                 = [[ZVRulerView alloc] initWithFrame:CGRectMake(0, 0, dialGap * 10, 50)];
            ruleView.backgroundColor = [UIColor blackColor];
            ruleView.tag             = 9527;
            ruleView.unit            = _unit;
            [cell.contentView addSubview:ruleView];
        }
        ruleView.item = indexPath.item;
        ruleView.intervalDay = _intervalDay;
        ruleView.minValue = _step * 10.f * (indexPath.item - 1); //  _step 6 * 10个刻度  * item
        ruleView.maxValue = _step * 10.f * indexPath.item; //  _step 6 * 10个刻度  * item
        [ruleView setNeedsDisplay];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"select indexPath.item== %ld", indexPath.item);
}

- (CGSize )collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == 0 || indexPath.item == _stepNum + 1) {
        return CGSizeMake(self.frame.size.width/2, 50.f);
    } else {
        return CGSizeMake(dialGap * 10.f, 50.f);
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0.f;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0.f;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGPoint point = [[touches anyObject] locationInView:self];
    if (point.y < self.frame.size.height - 50 - 20) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(ZVScrollSliderDidTouch:)]) {
            [self.delegate ZVScrollSliderDidTouch:self];
        }
    }
}

- (void)pauseTimer {
    if (self.timer) {
        CFRunLoopTimerInvalidate(self.timer);
        CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), self.timer, kCFRunLoopCommonModes);
    }
}

- (void)startTimer {
    [self configTimer];
}

- (void)configTimer {
    if (self.timer) {
        CFRunLoopTimerInvalidate(self.timer);
        CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), self.timer, kCFRunLoopCommonModes);
    }
    
    __weak __typeof(self) weakSelf = self;
    CFRunLoopTimerRef timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + 60, 60, 0, 0, ^(CFRunLoopTimerRef timer) {
        [weakSelf autoScroll];
        
    });
    
    self.timer = timer;
    CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes);
}

- (void)autoScroll {
    NSLog(@"self.collectionView.contentOffset.x=%f", self.collectionView.contentOffset.x);
    CGFloat minutes = (CGFloat)(dialGap / 6.00f);
    self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x + minutes , 0);
    [self updateOffset];

}

#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //NSLog(@"已经开始滑动");
    NSLog(@"scrollView.contentOffset.x==%f", scrollView.contentOffset.x);
    if (_scrollByHand) {
        [self pauseTimer];
        CGFloat value = scrollView.contentOffset.x/(dialGap);//滑了多少个刻度
        _valueTF.text = [self offsetWithSize:value];
    }
}

/**
 返回时间字符串
 
 @param scale 偏移了多少个刻度
 @return 时间 01：20
 */
- (NSString *)offsetWithSize:(CGFloat)scale {
    NSString *str = nil;
    int value = scale *_step;//偏移的刻度个数 * 单位刻度值
    int hour = value / 60 % 24;
    int min = value % 60 ;
    if (hour < 10 && min < 10 ) {
        str = [NSString stringWithFormat:@"0%d:0%d", hour, min];
    }
    
    if (hour < 10 && min > 9 ) {
        str = [NSString stringWithFormat:@"0%d:%d", hour, min];
    }
    
    if (hour > 9 && min < 10 ) {
        str = [NSString stringWithFormat:@"%d:0%d", hour, min];
    }
    
    if (hour > 9 && min > 9 ) {
        str = [NSString stringWithFormat:@"%d:%d", hour, min];
    }
    CGFloat oneDayOffset = 24 * 10 *dialGap;
    //向上取整
    int32_t intervalDay = ceil(_collectionView.contentOffset.x / oneDayOffset);
    NSLog(@"intervalDay==%d", intervalDay);
    if (intervalDay == 0) {
        intervalDay = 1;
    }
   
    NSDate *intervalDate = [self currentDateIntervalDay:_intervalDay - intervalDay];
    NSString *dateStr = [self dateWithStr:intervalDate format:nil];
    NSLog(@"scrollView.contentOffset.x==%f  intervalDay==%d dateStr==%@", _collectionView.contentOffset.x, intervalDay, dateStr);
    str = [NSString stringWithFormat:@"%@ %@",dateStr, str];
    //NSLog(@"scrollViewDidScroll hour==%d min==%d value== %f",hour, min, scale);
    return str;
}
#pragma mark - 将要开始滑动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    // NSLog(@"将要开始滑动");
    _scrollByHand = YES;
    [self pauseTimer];
}

#pragma mark - 结束滑动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    //NSLog(@"手停止拖动");
    if (!decelerate) {//拖拽时没有滑动动画
        [self startTimer];
        CGFloat value = scrollView.contentOffset.x/(dialGap);//滑了多少个刻度
        [self setRealValue:value Animated:YES];
    }
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    //NSLog(@"将要减速");
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    //NSLog(@"减速停止"); round(x)返回x的四舍五入整数值
    //[self setRealValue:round(scrollView.contentOffset.x/(dialGap)) Animated:YES];
    CGFloat value = scrollView.contentOffset.x/(dialGap);//滑了多少个刻度
    [self setRealValue:value Animated:YES];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    //NSLog(@"当setcontenttoffset /scrollRectVisible:animated:完成时调用。如果没有动画，则不调用");
}
@end// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com
